﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using XRM.ActiveDirectoryService;
using XRM.Security.DataAccess.Enums;
using XRM.Security.DataAccess.Helpers;
using XRM.Security.DataAccess.Models;
using XRM.Security.WebUI.Enums;
using XRM.Security.WebUI.Helpers;
using XRM.Security.WebUI.Models.Common;
using XRM.Security.WebUI.Models.InfoSystem;
using XRM.Security.WebUI.Models.SystemUser;
using XRM.Security.WebUI.Models.UserHistory;
using XRM.Security.WebUI.Models.UserRegister;
using XRM.Security.WebUI.Models.UserSkzi;

namespace XRM.Security.WebUI.Controllers
{
    [System.Web.Mvc.Authorize]
    public class UserRegisterController : BaseController
    {
        #region Index

        [System.Web.Mvc.Authorize( Roles = "Administrator, UsersReestrSertificateEditor, UsersReestrSkziEditor, UsersReestrSoftwareEditor" )]
        public ActionResult Index(string text, bool? showAll)
        {
            var userRegisters = UserRegisterRepository.GetAll();
            if (!string.IsNullOrEmpty(text))
                userRegisters = userRegisters.Where(x => (x.LastName + " " + x.FirstName + " " + x.MotherName).Replace("ё", "е").Contains(text.Replace("ё", "е")) ||
                    x.Department.Name.Replace("ё", "е").Contains(text.Replace("ё", "е")) || (!string.IsNullOrEmpty(x.Post) && x.Post.Replace("ё", "е").Contains(text.Replace("ё", "е"))));
            if ((!showAll.HasValue) || (!showAll.Value))
                userRegisters = userRegisters.Where( x => x.Status.Equals( (int)UserStatus.Work ) );

            var model = new UserRegisterListModel
            {
                TextFilter = text,
                ShowAllFilter = showAll.HasValue && showAll.Value,
                UserList = userRegisters.OrderBy(s => s.LastName).ThenBy(s => s.FirstName).AsEnumerable().Select( item => new UserRegisterModel( item ) ).ToList()
            };
            return View(model);
        }

        [System.Web.Mvc.HttpPost]
        [System.Web.Mvc.Authorize( Roles = "Administrator, UsersReestrSertificateEditor, UsersReestrSkziEditor, UsersReestrSoftwareEditor" )]
        public ActionResult Filter(UserRegisterListModel model)
        {
            if (!ModelState.IsValid)
            {
                ShowAlert(AlertType.Error, GetModelErrors());
                return View("Index", model);
            }

            return RedirectToAction("Index", new { text = model.TextFilter, showAll = model.ShowAllFilter });
        }

        #endregion

        #region Edit

        [System.Web.Mvc.HttpGet]
        [System.Web.Mvc.Authorize( Roles = "Administrator, UsersReestrSertificateEditor, UsersReestrSkziEditor, UsersReestrSoftwareEditor" )]
        public ActionResult Edit(int id)
        {
            var userRegister = UserRegisterRepository.Get( id );
            if (userRegister == null)
                throw new HttpResponseException(HttpStatusCode.NotFound);

            var model = new UserRegisterModel(userRegister);
            model.Init(DataManager);
            return View(model);
        }

        [System.Web.Mvc.HttpPost]
        [System.Web.Mvc.Authorize( Roles = "Administrator, UsersReestrSertificateEditor, UsersReestrSkziEditor, UsersReestrSoftwareEditor" )]
        public ActionResult Edit(UserRegisterModel model)
        {
            model.Init(DataManager);
            
            if (!ModelState.IsValid)
            {
                return View(model);
            }

            UserRegisterModel oldUser = null;
            UserRegister userRegister;
            if (model.IsEdit)
            {
                userRegister = UserRegisterRepository.Get(model.Id);
                if (userRegister == null)
                    throw new HttpResponseException(HttpStatusCode.BadRequest);

                oldUser = new UserRegisterModel(userRegister);
            }
            else
            {
                userRegister = new UserRegister();
            }

            // Если изменили статус на Уволен или В отпуске удаляем СКЗИ
            if (model.IsEdit && userRegister.Status == (int)UserStatus.Work &&
                (model.Status == UserStatus.NotWork || model.Status == UserStatus.Vacation))
            {
                var skziList = userRegister.Skzis.Where(s => s.DeleteDate == null).ToList();
                const string reasonComment = "Пользователь уволен/в длительном отпуске";
                foreach (var item in skziList)
                {
                    item.DeleteDate = DateTime.Today.Date;
                    item.DeleteReason = reasonComment;
                    item.DeleteSystemUserId = UserPrincipal.UserId;
                }
                foreach (var userPc in userRegister.PCs)
                {
                    userPc.PC.IsDeleted = true;
                }
                foreach (var systemInfo in userRegister.InfoSystems.Where(s => s.RevokeDate == null).ToList())
                {
                    systemInfo.RevokeDate = DateTime.Now;
                    systemInfo.RevokeSystemUserId = UserPrincipal.UserId;
                    systemInfo.RevokeReason = reasonComment;
                }
                foreach (var request in userRegister.Requests.Where(s => s.Status == (int)RequestStatus.InPart || s.Status == (int)RequestStatus.InWork).ToList())
                {
                    request.Status = (int)RequestStatus.Error;
                    request.CloseDate = DateTime.Now;
                }
            }

            model.ApplyChanges( userRegister );

            if (!model.IsEdit)
            {
                UserRegisterRepository.Add(userRegister);
                ShowAlert(AlertType.Success, "Пользователь создан успешно");
            }
            else
            {
                AddUserHistory(oldUser, model, null);
                UserRegisterRepository.Update(userRegister);
                ShowAlert(AlertType.Success, "Информация о пользователе успешно сохранена.");
            }
            return RedirectToAction("Index");
        }

        #endregion

        #region InfoSystem

        [System.Web.Mvc.Authorize( Roles = "Administrator, UsersReestrSertificateEditor, UsersReestrSkziEditor, UsersReestrSoftwareEditor" )]
        public ActionResult EditInfoSystem(int id)
        {
            UserRegisterInfoSystemEditModel model = new UserRegisterInfoSystemEditModel();

            List<UserInfoSystem> userInfoSystems = UserInfoSystemRepository.GetAll(x => x.UserRegisterId.Equals(id)).ToList();
            foreach (var item in userInfoSystems)
                model.InfoSystemList.Add(new UserInfoSystemModel(item));
            model.GetInfoSystemAll(InfoSystemRepository.GetAll(x => x.InMaintenance).ToList().Where(x => !model.InfoSystemList.Any(x2 => (!x2.RevokeDate.HasValue) && x.InfoSystemId.Equals(x2.InfoSystemId))).ToList());
            model.UserRegisterId = id;
            model.GetUserRegister(UserRegisterRepository.Get(id));
            if (model.InfoSystemList.All(s => s.RevokeDate != null))
            {
                model.ShowRevoke = true;
            }
            return PartialView(model);
        }

        [System.Web.Mvc.HttpPost]
        [System.Web.Mvc.Authorize( Roles = "Administrator, UsersReestrSertificateEditor, UsersReestrSkziEditor, UsersReestrSoftwareEditor" )]
        public ActionResult GrantInfoSystem(UserRegisterInfoSystemEditModel model)
        {
            if (ModelState.IsValid)
            {
                UserRegister_GrantInfoSystem(model.UserRegisterId, model.InfoSystemId, (int?)null);
            }

            return RedirectToAction("EditInfoSystem", new { id = model.UserRegisterId });
        }

        [System.Web.Mvc.Authorize( Roles = "Administrator, UsersReestrSertificateEditor, UsersReestrSkziEditor, UsersReestrSoftwareEditor" )]
        public ActionResult RevokeInfoSystemDialog( int id )
        {
            return View( new RevokeInfoSystemModel { Id = id, RevokeDate = DateTime.Today });
        }

        [System.Web.Mvc.HttpPost]
        [System.Web.Mvc.Authorize( Roles = "Administrator, UsersReestrSertificateEditor, UsersReestrSkziEditor, UsersReestrSoftwareEditor" )]
        public ActionResult RevokeInfoSystemDialog(RevokeInfoSystemModel model)
        {
            if (!ModelState.IsValid)
            {
                return View( model );
            }
            UserInfoSystem userInfoSystem = UserInfoSystemRepository.Get(model.Id);
            userInfoSystem.RevokeDate = DateTime.Now;
            userInfoSystem.RevokeSystemUserId = UserPrincipal.UserId;
            userInfoSystem.RevokeReason = model.RevokeReason;
            userInfoSystem.InfoSystem.CertRegisterInfoSystems.Clear();
            UserInfoSystemRepository.Update(userInfoSystem);
            AddUserHistory_DelInfoSystem( userInfoSystem.UserRegisterId, userInfoSystem.InfoSystemId );

            return Json( new { success = true } );
        }

        #endregion

        #region PC

        [System.Web.Mvc.Authorize( Roles = "Administrator, UsersReestrSertificateEditor, UsersReestrSkziEditor, UsersReestrSoftwareEditor" )]
        public ActionResult EditPC(int id)
        {
            UserRegisterPCEditModel model = new UserRegisterPCEditModel();

            List<UserPC> userPC = UserPCRepository.GetAll(x => x.UserRegisterId.Equals(id) && !x.PC.IsDeleted).ToList();
            foreach (var item in userPC)
            {
                PCModel itemModel = new PCModel(item);
                model.PCList.Add(itemModel);
            }
            model.UserRegisterId = id;
            model.GetUserRegister(UserRegisterRepository.Get(id));

            return PartialView(model);
        }

        [System.Web.Mvc.HttpPost]
        [System.Web.Mvc.Authorize(Roles = "Administrator, UsersReestrSertificateEditor, UsersReestrSkziEditor, UsersReestrSoftwareEditor")]
        public ActionResult DeletePC(int userRegisterId, int pcId)
        {
            var userPc = UserPCRepository.Get( x => x.PCId == pcId && x.UserRegisterId == userRegisterId );
            if ( userPc == null )
                throw new HttpResponseException(HttpStatusCode.BadRequest);

            if (UserSkziRepository.GetAll(s => s.DeleteDate == null && s.UserRegisterId == userRegisterId && s.PCId == pcId).Any())
            {
                return JsonError( "Для удаления системного блока необходимо удалить все установленные на нем СКЗИ." );
            }

            if (RequestWorkKindParamRepository.GetAll(s => s.PCId == pcId && s.RequestWorkKind.CloseDate == null).Any())
            {
                return JsonError( "Невозможно удалить системный блок, т.к. он используется в открытой заявке." );
            }

            var pc = userPc.PC;
            pc.IsDeleted = true;
            foreach (var cert in pc.Certificates.ToList())
            {
                cert.PCId = null;
            }
            PCRepository.Update( pc );
            HistoryService.DeletePC( userPc );
            
            return Json(new {isSuccess = true});
        }

        [System.Web.Mvc.HttpGet]
        [System.Web.Mvc.Authorize(Roles = "Administrator, UsersReestrSertificateEditor, UsersReestrSkziEditor, UsersReestrSoftwareEditor")]
        public ActionResult AddUserPCDialog(int userId, int? pcId)
        {
            UserRegisterAddPCModel model;
            if (pcId.HasValue)
            {
                var pc = PCRepository.Get( pcId );
                if (pc == null || pc.IsDeleted)
                    throw new HttpResponseException(HttpStatusCode.BadRequest);
                model = new UserRegisterAddPCModel(pc);
            }
            else
            {
                model = new UserRegisterAddPCModel();
            }
            model.UserRegisterId = userId;
            return View(model);
        }

        [System.Web.Mvc.HttpPost]
        [System.Web.Mvc.Authorize(Roles = "Administrator, UsersReestrSertificateEditor, UsersReestrSkziEditor, UsersReestrSoftwareEditor")]
        public ActionResult AddUserPCDialog(UserRegisterAddPCModel model)
        {
            if (!ModelState.IsValid)
            {
                return View(model);
            }
            PC dbItem;
            if ( model.IsEdit )
            {
                dbItem = PCRepository.Get( model.Id );
                HistoryService.UpdatePc( model, dbItem );
            }
            else
            {
                dbItem = new PC();
                HistoryService.AddPc( model );
            }
            model.ApplyChanges( dbItem, PCStickerRepository );

            if ( model.IsEdit )
            {
                PCRepository.Update( dbItem );
            }
            else
            {
                PCRepository.Add( dbItem );
                UserPCRepository.Add( new UserPC { PCId = dbItem.PCId, UserRegisterId = model.UserRegisterId } );
            }
            return Json(new { success = true });
        }

        #endregion

        #region SCSI

        [System.Web.Mvc.Authorize( Roles = "Administrator, UsersReestrSertificateEditor, UsersReestrSkziEditor" )]
        public ActionResult EditSkzi(int id)
        {
            var skziList = UserSkziRepository.GetAll(x => x.UserRegisterId.Equals(id))
                .Select(s => new UserRegisterSkziItem
                    {
                            Id = s.UserSkziId,
                            SetupDate = s.SetupDate,
                            DeleteDate = s.DeleteDate,
                            DeleteReason = s.DeleteReason,
                            PCSerialNumber = s.PC.SerialNumber,
                            SkziCopyNumber = s.CopyNumber,
                            SkziKindName = s.SkziKind.ShortName,
                            SkziKindId = s.SkziKindId,
                            SetupSystemUser = s.SetupSystemUser,
                            IsDeletedSkzi = s.SkziKind.IsDeleted
                    })
                .ToList();
            var model = new UserRegisterSkziEditModel
                {
                    UserRegisterId = id,
                    SkziList = skziList
                };
            if ( model.SkziList.All( s => s.DeleteDate.HasValue ) )
                model.ShowDelete = true;
            return PartialView(model);
        }

        [System.Web.Mvc.HttpGet]
        [System.Web.Mvc.Authorize(Roles = "Administrator, UsersReestrSkziEditor")]
        public ActionResult AddUserSkziDialog(int? userId)
        {
            var model = new UserSkziModel();
            if (userId.HasValue)
            {
                model.UserRegisterId = userId;
            }
            else
            {
                model.AllowUserChange = true;
            }

            model.Init(DataManager);
            return View(model);
        }

        [System.Web.Mvc.HttpPost]
        [System.Web.Mvc.Authorize(Roles = "Administrator, UsersReestrSkziEditor")]
        public ActionResult AddUserSkziDialog(UserSkziModel model)
        {
            model.Init(DataManager);
            
            if (!ModelState.IsValid)
            {
                return View(model);
            }

            UserSkzi existsSkzi = UserSkziRepository.GetAll(x => x.SkziKindId == model.SkziKindId && x.CopyNumber == model.CopyNumber && !x.DeleteDate.HasValue).SingleOrDefault();
            if (existsSkzi != null)
            {
                ShowAlert(AlertType.Error, "Вид СКЗИ и номер экземпляра уже установлены пользователю '" + existsSkzi.UserRegister.FullName() + "'");
                return View(model);
            }

            UserSkziModel oldModel = null;
            UserSkzi dbItem = new UserSkzi();
            if (model.IsEdit)
            {
                dbItem = UserSkziRepository.Get(model.Id);
                oldModel = new UserSkziModel(dbItem);
            }
            else
            {
                dbItem.SetupDate = DateTime.Today.Date;
                dbItem.UserRegisterId = model.UserRegisterId.Value;
                dbItem.SetupSystemUserId = UserPrincipal.UserId;
            }

            dbItem.CopyNumber = model.CopyNumber;
            dbItem.PCId = model.PCId.Value;
            dbItem.SkziKindId = model.SkziKindId.Value;

            if (model.IsEdit)
            {
                UserSkziRepository.Update(dbItem);
                AddUserHistory_EditScsi(oldModel, model);
                ShowAlert(AlertType.Success, "Информация об СКЗИ обновлена успешно");
            }
            else
            {
                UserSkziRepository.Add(dbItem);
                AddUserHistory_AddScsi(dbItem.UserSkziId, null);
            }

            return Json(new { success = true });
        }

        [System.Web.Mvc.HttpGet]
        [System.Web.Mvc.Authorize(Roles = "Administrator, UsersReestrSkziEditor")]
        public ActionResult DeleteUserSkziDialog(int userSkziId)
        {
            UserRegisterDeleteSkziModel skziModel = new UserRegisterDeleteSkziModel();
            skziModel.Id = userSkziId;

            UserSkzi dbItem = UserSkziRepository.Get(userSkziId);
            if (dbItem.DeleteDate.HasValue)
            {
                skziModel.DeleteDate = dbItem.DeleteDate.Value;
                skziModel.DeleteReason = dbItem.DeleteReason;
                skziModel.IsEdit = true;
            }
            else
            {
                skziModel.DeleteDate = DateTime.Today;
                skziModel.IsEdit = false;
            }
            return View(skziModel);
        }

        [System.Web.Mvc.HttpPost]
        [System.Web.Mvc.Authorize(Roles = "Administrator, UsersReestrSkziEditor")]
        public ActionResult DeleteUserSkziDialog(UserRegisterDeleteSkziModel skziModel)
        {
            if (!ModelState.IsValid)
            {
                return View(skziModel);
            }

            var dbItem = UserSkziRepository.Get(skziModel.Id);
            if (dbItem == null || dbItem.DeleteDate != null)
                throw new HttpResponseException(HttpStatusCode.BadRequest);

            if (dbItem.SetupDate > skziModel.DeleteDate)
            {
                ModelState.AddModelError("DeleteDate", "Дата удаления не может быть меньше даты установки");
                return View( skziModel );
            }
            dbItem.DeleteDate = skziModel.DeleteDate;
            dbItem.DeleteReason = skziModel.DeleteReason;
            dbItem.DeleteSystemUserId = UserPrincipal.UserId;
            UserSkziRepository.Update(dbItem);
            AddUserHistory_DelScsi(dbItem.UserSkziId, (int?) null);

            return Json(new { success = true });
        }

        #endregion

        #region Certificates

        [System.Web.Mvc.Authorize(Roles = "Administrator, UsersReestrSkziEditor, UsersReestrSertificateEditor")]
        public ActionResult EditCert(int id)
        {
            var userRegister = UserRegisterRepository.Get( id );
            var model = new UserRegisterCertEditModel
                {
                        UserRegisterId = userRegister.UserRegisterId,
                        UserStatus = (UserStatus)userRegister.Status,
                        CertList = CertRegisterRepository.GetByUserId(id).OrderByDescending(s => s.FromDate).ToSearchItems()
                };
            return PartialView(model);
        }

        #endregion

        #region AD

        [System.Web.Mvc.HttpGet]
        [System.Web.Mvc.Authorize(Roles = "Administrator, UsersReestrSkziEditor, UsersReestrSertificateEditor, UsersReestrSoftwareEditor")]
        public ActionResult ADUsersDialog()
        {
            ADUserDialogFilterModel model = new ADUserDialogFilterModel();
            return View(model);
        }

        [System.Web.Mvc.HttpPost]
        [System.Web.Mvc.Authorize(Roles = "Administrator, UsersReestrSkziEditor, UsersReestrSertificateEditor, UsersReestrSoftwareEditor")]
        public ActionResult ADUsersDialog(ADUserDialogFilterModel model)
        {
            if (model.UserDialogSubmitAction.Equals("search"))
            {
                if (!ModelState.IsValid)
                {
                    ModelState.Remove("SubmitAction");
                    model.UserDialogSubmitAction = "";

                    ShowAlert(AlertType.Error, GetModelErrors());
                    return View(model);
                }
            }
            else
            {
                ModelState.Clear();
                model.UserRegisterModel = new UserRegisterModel
                    {
                        LastName = model.LastNameFilter,
                        FirstName = model.FirstNameFilter
                    };
                model.UserRegisterModel.Init(DataManager);
                model.LastNameFilter = null;
                model.FirstNameFilter = null;
            }
            return View(model);
        }

        [System.Web.Mvc.Authorize(Roles = "Administrator, UsersReestrSkziEditor, UsersReestrSertificateEditor, UsersReestrSoftwareEditor")]
        public ActionResult ADUsersGrid(string lname, string fname)
        {
            var model = new ADUserDialogModel();
            model.GetDepartmentAll(DepartmentRepository.GetAll(x => x.IsDeleted == false).OrderBy(x => x.Name).ToList());
            model.GetDepartmentAddressAll(DepartmentAddressRepository.GetAll(x => x.DepartmentId == model.DepartmentId).OrderBy(x => x.Address).ToList());
            model.ADUserList = ActiveDirectoryService.Search( lname, fname );
            return View("ADUsersGrid", model);
        }

        [System.Web.Mvc.HttpPost]
        [System.Web.Mvc.Authorize(Roles = "Administrator, UsersReestrSkziEditor, UsersReestrSertificateEditor, UsersReestrSoftwareEditor")]
        public ActionResult ADUserChoice(ADUserDialogModel model)
        {
            if (!ModelState.IsValid)
            {
                ShowAlert(AlertType.Error, GetModelErrors());
                return View("ADUsersDialog");
            }

            var adUser = ActiveDirectoryService.SearchByUserName( model.SelectedLogin ).FirstOrDefault();
            if (adUser == null)
                throw new HttpResponseException(HttpStatusCode.BadRequest);

            var dbItem = UserRegisterRepository.GetAll(x => x.LastName == adUser.LastName && x.FirstName == adUser.FirstName).ToList()
                .FirstOrDefault(x => x.FullName().ToLower() == adUser.FullName.ToLower());
            if (dbItem == null)
            {
                dbItem = new UserRegister {
                        LastName = adUser.LastName,
                        FirstName = adUser.FirstName,
                        MotherName = adUser.MiddleName,
                        Status = (int)UserStatus.Work,
                        DepartmentId = model.DepartmentId,
                        DepartmentAddressId = model.DepartmentAddressId,
                        IsADUser = true
                };
                UserRegisterRepository.Add(dbItem);
            }
            return Json( new { success = true, userId = dbItem.UserRegisterId, userName = dbItem.FullName() } );
        }

        [System.Web.Mvc.HttpPost]
        [System.Web.Mvc.Authorize(Roles = "Administrator, UsersReestrSkziEditor, UsersReestrSertificateEditor, UsersReestrSoftwareEditor")]
        public ActionResult AddUserRegisterChoice(UserRegisterModel model)
        {
            if (!ModelState.IsValid)
            {
                model.Init(DataManager);
                return View("ADUsersDialog", new ADUserDialogFilterModel { UserDialogSubmitAction = "add", UserRegisterModel = model });
            }

            var dbItem = new UserRegister();
            model.ApplyChanges(dbItem);
            UserRegisterRepository.Add(dbItem);
            return Json( new { success = true, userId = dbItem.UserRegisterId, userName = dbItem.FullName() } );
        }
        
        [System.Web.Mvc.HttpPost]
        public JsonResult Autocomplete(string term)
        {
            var searchList = UserRegisterRepository.GetAll().Where( s => s.Status == (int)UserStatus.Work).FilterByFullName(term)
                .AsEnumerable().Select(s => new {Id = s.UserRegisterId, FullName = s.FullName(), Post = s.Post }).ToList();
            return Json( searchList, JsonRequestBehavior.AllowGet );
        }

        #endregion

        [System.Web.Mvc.HttpPost]
        public JsonResult PCList(int userId)
        {
            var result = UserPCRepository.GetPCByUserId(userId).ToSelectedList();//.AddFirst(SelectedListHelper.EmptyPCItem);
            return Json( result.ToJsonObject(), JsonRequestBehavior.AllowGet );
        }

        [System.Web.Mvc.HttpPost]
        public JsonResult InfoSystemList(int userId)
        {
            var searchList = UserInfoSystemRepository.GetAll(x => x.UserRegisterId.Equals(userId) && !x.RevokeDate.HasValue).ToList();
            List<InfoSystemModel> resultList = new List<InfoSystemModel>();
            foreach (var item in searchList)
            {
                resultList.Add(new InfoSystemModel { Id = item.InfoSystemId, InfoSystemName = item.InfoSystem.InfoSystemName });
            }
            resultList.Insert(0, new InfoSystemModel { Id = -1, InfoSystemName = "(Выберите информационную систему)" });
            return Json(resultList, JsonRequestBehavior.AllowGet);
        }

        [System.Web.Mvc.Authorize(Roles = "Administrator, UsersReestrSkziEditor, UsersReestrSertificateEditor, UsersReestrSoftwareEditor")]
        public ActionResult UserHistory(int id, int historyGroup)
        {
            var historyGroups = historyGroup == (int)UserHistoryGroup.Scsi ? new[] { historyGroup, (int)UserHistoryGroup.Pc } : new[] { historyGroup };
            var model = UserHistoryRepository.GetAll(x => x.UserRegisterId == id && historyGroups.Contains(x.HistoryGroup))
                .OrderByDescending(x => x.HistoryDate).Select(item => new HistoryItem
                    {
                            Date = item.HistoryDate,
                            Text = item.HistoryText,
                            SystemUser = item.SystemUser
                    }).ToList();
            return PartialView("History", model);
        }
    }
}
